$(function() {
    var form = layui.form
    $.ajaxPrefilter(function(option) {
        option.url = 'http://ajax.frontend.itheima.net' + option.url
        if (option.url.indexOf('/my') !== -1) {
            option.headers = {
                Authorization: localStorage.getItem('token') || ''
            }
            option.complete = function(res) {
                if (res.responseJSON.status == 1 && res.responseJSON.message === '身份认证失败！') {
                    localStorage.setItem('token', '')
                    location.href = './login.html'
                }
            }
        }
    })
    form.verify({
        pwd: [/^[\S]{6,12}$/, '密码必须6到12位，且不能出现空格'],
        samePwd: function(value) {
            if (value == $('[name=oldPwd]').val()) {
                return '新密码不能相同'
            }
        },
        rePwd: function(value) {

            if (value !== $('[name=newPwd]').val()) {
                return '两次密码不一致！'
            }
        }
    })
    $('.layui-form').on('submit', function(e) {
        e.preventDefault()

        $.ajax({
            method: 'POST',
            url: '/my/updatepwd',
            data: $(this).serialize(),
            success: function(res) {
                if (res.status !== 0) {
                    return layui.layer.msg('更新密码失败！')
                }
                layui.layer.msg('更新密码成功！')
                    // 重置表单
                $('.layui-form')[0].reset()
            }
        })
    })
})